package com.xxh.user.service;

import com.xxh.dataaccess.entity.User;
import com.xxh.user.UserApplication;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;

@Service
public class EmailService {


    @Value("${spring.mail.username}")
    String myEmailAddr;
    @Autowired
    JavaMailSender mailSender;

    public void sendEmail(User user) throws MessagingException, IOException, TemplateException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        helper.setFrom(myEmailAddr);
        helper.setTo(user.getEmail());
        helper.setSubject("注册提示");
        helper.setSentDate(new Date());

        //freemark基本配置
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
        //配置模板位置
        ClassLoader loader = UserApplication.class.getClassLoader();
        configuration.setClassLoaderForTemplateLoading(loader,"templates");

        //获取模板
        Template template = configuration.getTemplate("registerWelcome.ftlh");
        StringWriter out=new StringWriter();
        //1 要渲染的数据模型
        //2 渲染后输出为字符流
        template.process(user,out);
        //3 渲染完成的字符流变成html发过去
        helper.setText(out.toString(),true);
        mailSender.send(message);

    }
}
